package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"videoProject/src/filemanage/api/internal/svc"
	"videoProject/src/filemanage/api/internal/types"
)

const maxFileSize = 10 << 20 // 10 MB

type UploadRequestLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadRequestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadRequestLogic {
	return &UploadRequestLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadRequestLogic) WriteFiles(Filename string, file multipart.File) {
	dst, err := os.Create(Filename)
	if err != nil {
		return
	}

	defer dst.Close()

	// 将文件内容复制到目标文件
	_, err = io.Copy(dst, file)
	if err != nil {
		return
	}
}

func (l *UploadRequestLogic) UploadRequest(r *http.Request) (resp *types.UploadFileResponse, err error) {
	// todo: add your logic here and delete this line
	fmt.Println("Uploading................................................................")
	_ = r.ParseMultipartForm(maxFileSize)
	//_ = r.ParseForm() // 返回多个表单字段
	files, handler, err := r.FormFile("file")
	if err != nil {
		return nil, err
	}
	fmt.Printf("Uploaded File: %+v\n", handler.Filename)
	fmt.Printf("File Size: %+v\n", handler.Size)
	fmt.Printf("MIME Header: %+v\n", handler.Header)

	l.WriteFiles(handler.Filename, files)
	//Content, err := io.ReadAll(files)
	//
	//fileReq := &file.UploadFileRequest{
	//	FileName: handler.Filename,
	//	Content:  Content,
	//}
	//res, err := l.svcCtx.FileRpc.UploadFile(l.ctx, fileReq)
	//if err != nil {
	//	return nil, err
	//}
	//return &types.UploadFileResponse{
	//	Success: res.Success,
	//	Message: res.Message,
	//}, nil

	return &types.UploadFileResponse{
		Success: true,
		Message: "上传成功",
	}, nil
}
